package cn.itsource.controller;

import cn.itsource.domain.User;
import cn.itsource.dto.ModifyPasswordDto;
import cn.itsource.exception.BusinessException;
import cn.itsource.mapper.UserMapper;
import cn.itsource.service.UserService;
import cn.itsource.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
public class SystemController {

    @Autowired
    private UserService userService;

    //接收参数：1.参数名 2.对象【自定义对象，Api自带的对象Map】 3.路径表达式
    //浏览器存储技术：
    //cookie：存储大小4KB，跨域访问不能自动携带Cookie
    //localStorage：当前浏览器有效，可以跨窗口获取数据，存储大小5M
    //sessionStorage：当前窗口有效，不能跨窗口获取数据，存储大小5M

    @PostMapping("/login")
    public AjaxResult login(@RequestBody Map<String, String> map, HttpSession session) {
        try {  //登录成功
            User user = userService.tologin(map);
            //将登录信息存放在session中，
            session.setAttribute("USER_IN_SESSION", user);

            return AjaxResult.me().setObj(user);
        } catch (BusinessException e) {
            return new AjaxResult(false, e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "网络有点拥挤繁忙，等等再试");
        }
    }

    //修改密码
    @PostMapping("/modifyPassword")
    public AjaxResult modifyPassword(@RequestBody ModifyPasswordDto modifyPasswordDto, HttpServletRequest request){
        try {
            User user = (User) request.getSession().getAttribute("USER_IN_SESSION");
            userService.modifyPassword(modifyPasswordDto,user);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false,"密码修改失败");
        }

    }

}
